package com.whpost.service.service.t;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TFilesMapper;
import com.whpost.service.dao.t.TPermissionDao;
import com.whpost.service.dao.t.TXzjgDao;
import com.whpost.service.dao.t.TXzjgLbDao;
import com.whpost.service.entity.t.*;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TXzjgServices extends BaseServices<TXzjgDao, TXzjg> {

    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private TXzjgLbDao tXzjgLbDao;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TXzjg> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TXzjg> TXzjgListInfo = new ListInfo<>();
            QueryWrapper<TXzjg> tXzjgQueryWrapper = new QueryWrapper<TXzjg>();
            if (!StringUtils.isEmpty(cxmc)){
                tXzjgQueryWrapper.like("name",cxmc);
            }else{
                tXzjgQueryWrapper.eq("1","1");
            }
            tXzjgQueryWrapper.orderByAsc("xh");

            IPage<TXzjg> TXzjgIPage = getBaseMapper().selectPage(page,tXzjgQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(TXzjgIPage.getTotal());
            pageInfo.setCurPage(TXzjgIPage.getCurrent());
            pageInfo.setPageSize(TXzjgIPage.getSize());
            pageInfo.setPageTotal(TXzjgIPage.getPages());

            TXzjgListInfo.setPageInfo(pageInfo);
            TXzjgListInfo.setListInfo(TXzjgIPage.getRecords());

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",TXzjgListInfo);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo tree(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(500, "用户信息丢失！", null);
        } else {
            Map<String, Object> rtnMap = new HashMap<>();
            String treejson = getTree();
            rtnMap.put("treejson", JSON.parse("[" + treejson + "]"));
            ResultInfo resultInfo = new ResultInfo(0, "成功返回！", rtnMap);
            return backRtn(resultInfo, loginId);
        }
    }

    public String getTree(){
        TXzjg tXzjg = new TXzjg();
        TXzjg tXzjgSon = new TXzjg();
        String treejson = "";
        // 一级菜单
        List<TXzjg> tXzjgList = new ArrayList<>();
        tXzjgList = getBaseMapper().selectList(new QueryWrapper<TXzjg>().eq("jb", "1").orderByAsc("xh"));

        // 二级菜单
        List<TXzjg> tXzjgListSon = new ArrayList<>();
        for (int i = 0; i < tXzjgList.size(); i++) {
            tXzjg = tXzjgList.get(i);

            // 构建经纬度数组字符串
            String coordinates = "null";
            if (tXzjg.getWdjd() != null && tXzjg.getWdwd() != null) {
                coordinates = "[" + tXzjg.getWdjd() + ", " + tXzjg.getWdwd() + "]";
            }

            // 构建一级菜单JSON，添加新字段和coordinates属性
            treejson += "{\"id\":\"" + tXzjg.getId() + "\","
                    + "\"name\":\"" + tXzjg.getName() + "\","
                    + "\"dz\":\"info?lx=1&id=" + tXzjg.getId() + "\","
                    + "\"open\":false,"
                    + "\"fzr\":\"" + (tXzjg.getFzr() != null ? tXzjg.getFzr() : "") + "\","
                    + "\"wddh\":\"" + (tXzjg.getWddh() != null ? tXzjg.getWddh() : "") + "\","
                    + "\"wddz\":\"" + (tXzjg.getWdwd() != null ? tXzjg.getWddz() : "") + "\","
                    + "\"wdyysj\":\"" + (tXzjg.getWdyysj() != null ? tXzjg.getWdyysj() : "") + "\","
                    + "\"wdyb\":\"" + (tXzjg.getWdyb() != null ? tXzjg.getWdyb() : "") + "\","
                    + "\"wglj\":\"" + (tXzjg.getWglj() != null ? tXzjg.getWglj() : "") + "\","
                    + "\"wdms\":\"" + (tXzjg.getWdms() != null ? tXzjg.getWdms() : "") + "\","
                    + "\"sfqu\":\"" + (tXzjg.getSfqu() != null ? tXzjg.getSfqu() : "") + "\","
                    + "\"wdjd\":" + (tXzjg.getWdjd() != null ? tXzjg.getWdjd() : "null") + ","
                    + "\"wdwd\":" + (tXzjg.getWdwd() != null ? tXzjg.getWdwd() : "null") + ","
                    + "\"xzjg_lb\":" + tXzjg.getXzjgLb() + ","
                    + "\"coordinates\":" + coordinates + "},";

            // 放入二级菜单
            tXzjgListSon = getBaseMapper().getXzjgXjNoRoot(tXzjg.getId());
            for (int k = 0; k < tXzjgListSon.size(); k++) {
                tXzjgSon = tXzjgListSon.get(k);

                // 构建经纬度数组字符串
                String sonCoordinates = "null";
                if (tXzjgSon.getWdjd() != null && tXzjgSon.getWdwd() != null) {
                    sonCoordinates = "[" + tXzjgSon.getWdjd() + ", " + tXzjgSon.getWdwd() + "]";
                }

                // 构建二级菜单JSON，添加新字段和coordinates属性
                treejson += "{\"id\":\"" + tXzjgSon.getId() + "\","
                        + "\"pId\":\"" + tXzjgSon.getPid() + "\","
                        + "\"name\":\"" + tXzjgSon.getName() + "\","
                        + "\"dz\":\"info?lx=1&id=" + tXzjgSon.getId() + "\","
                        + "\"open\":false,"
                        + "\"fzr\":\"" + (tXzjgSon.getFzr() != null ? tXzjgSon.getFzr() : "") + "\","
                        + "\"wddh\":\"" + (tXzjgSon.getWddh() != null ? tXzjgSon.getWddh() : "") + "\","
                        + "\"wddz\":\"" + (tXzjgSon.getWddz() != null ? tXzjgSon.getWddz() : "") + "\","
                        + "\"wdyysj\":\"" + (tXzjgSon.getWdyysj() != null ? tXzjgSon.getWdyysj() : "") + "\","
                        + "\"wdyb\":\"" + (tXzjgSon.getWdyb() != null ? tXzjgSon.getWdyb() : "") + "\","
                        + "\"sfqu\":\"" + (tXzjgSon.getSfqu() != null ? tXzjgSon.getSfqu() : "") + "\","
                        + "\"wglj\":\"" + (tXzjgSon.getWglj() != null ? tXzjgSon.getWglj() : "") + "\","
                        + "\"wdms\":\"" + (tXzjgSon.getWdms() != null ? tXzjgSon.getWdms() : "") + "\","
                        + "\"wdjd\":" + (tXzjgSon.getWdjd() != null ? tXzjgSon.getWdjd() : "null") + ","
                        + "\"wdwd\":" + (tXzjgSon.getWdwd() != null ? tXzjgSon.getWdwd() : "null") + ","
                        + "\"xzjg_lb\":" + tXzjgSon.getXzjgLb() + ","
                        + "\"coordinates\":" + sonCoordinates + "},";
            }
        }

        // 处理最后一个逗号的问题
        if (treejson.length() > 0) {
            treejson = treejson.substring(0, treejson.length() - 1);
        }
        return treejson;
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",pid="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }
            Map<String,Object> rtnMap = new HashMap<>();

            TXzjg tXzjg = new TXzjg();
            if ("1".equals(lx)){
                tXzjg = new TXzjg();
                tXzjg = getBaseMapper().getXzjgById(id);
                rtnMap.put("tXzjg",tXzjg);

                QueryWrapper<TXzjg> tXzjgQueryWrapper = new QueryWrapper<TXzjg>();
                tXzjgQueryWrapper.le("jb",tXzjg.getJb()).ne("id",tXzjg.getId());
                if (null!=tXzjg.getPid()) tXzjgQueryWrapper.ne("id",tXzjg.getPid());
                List<TreeNode> qyjgTree = getTreeSelect(tXzjgQueryWrapper);   //禁用父节点
                rtnMap.put("qyjgTree",qyjgTree);

            }
            if (!StringUtils.isEmpty(pid)){
                TXzjg pXzjg = new TXzjg();
                pXzjg = getBaseMapper().getXzjgById(pid);
                if (null==pXzjg){
                    return new ResultInfo(500,"上级机构信息丢失！",null);
                }
                rtnMap.put("pXzjg",pXzjg);
            }

            List<TXzjgLb> tXzjgLbList = new ArrayList<TXzjgLb>();
            tXzjgLbList = tXzjgLbDao.selectList(null);

            rtnMap.put("tXzjgLbList",tXzjgLbList);

            ResultInfo resultInfo = new ResultInfo(0, "查询成功！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",jgmc="",jgh="",xsxh="",pid="";
            // 新增字段变量定义
            String fzr = "", wddh = "", wddz = "", wdyysj = "", wdyb = "", wdms = "";
            String wdjdStr = "", wdwdStr = "", xzjg_lbStr = "";
            BigDecimal wdjd = null, wdwd = null;
            Long xzjg_lb = 0L;

            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("jgmc")) {
                jgmc = jsonObject.getString("jgmc");
            }
            if (jsonObject.containsKey("jgh")) {
                jgh = jsonObject.getString("jgh");
            }
            if (jsonObject.containsKey("xsxh")) {
                xsxh = jsonObject.getString("xsxh");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }

            // 处理新增字段
            if (jsonObject.containsKey("fzr")) {
                fzr = jsonObject.getString("fzr");
            }
            if (jsonObject.containsKey("wddh")) {
                wddh = jsonObject.getString("wddh");
            }
            if (jsonObject.containsKey("wddz")) {
                wddz = jsonObject.getString("wddz");
            }
            if (jsonObject.containsKey("wdyysj")) {
                wdyysj = jsonObject.getString("wdyysj");
            }
            if (jsonObject.containsKey("wdyb")) {
                wdyb = jsonObject.getString("wdyb");
            }
            if (jsonObject.containsKey("wdms")) {
                wdms = jsonObject.getString("wdms");
            }
            if (jsonObject.containsKey("wdjd")) {
                wdjdStr = jsonObject.getString("wdjd");
                if (!StringUtils.isEmpty(wdjdStr)) {
                    try {
                        wdjd = new BigDecimal(wdjdStr);
                    } catch (NumberFormatException e) {
                        // 可以根据需要添加数字格式错误处理
                    }
                }
            }
            if (jsonObject.containsKey("wdwd")) {
                wdwdStr = jsonObject.getString("wdwd");
                if (!StringUtils.isEmpty(wdwdStr)) {
                    try {
                        wdwd = new BigDecimal(wdwdStr);
                    } catch (NumberFormatException e) {
                        // 可以根据需要添加数字格式错误处理
                    }
                }
            }
            if (jsonObject.containsKey("xzjg_lb")) {
                xzjg_lbStr = jsonObject.getString("xzjg_lb");
                if (!StringUtils.isEmpty(xzjg_lbStr)) {
                    try {
                        xzjg_lb = Long.parseLong(xzjg_lbStr);
                    } catch (NumberFormatException e) {
                        // 可以根据需要添加数字格式错误处理
                    }
                }
            }

            if (StringUtils.isEmpty(jgmc)){
                ResultInfo resultInfo = new ResultInfo(500, "机构名称不能为空！",null);
                return backRtn(resultInfo,loginId);
            }

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"xzjg.addDo");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TXzjg tXzjg = new TXzjg();
            TXzjg pXzjg = new TXzjg();
            if ("1".equals(lx)){
                tXzjg = getBaseMapper().selectById(id);
            }
            tXzjg.setName(jgmc);
            tXzjg.setZjm(ToolBean.getPy(jgmc));

            // 设置新增字段值
            tXzjg.setFzr(fzr);
            tXzjg.setWddh(wddh);
            tXzjg.setWddz(wddz);
            tXzjg.setWdyysj(wdyysj);
            tXzjg.setWdyb(wdyb);
            tXzjg.setWdms(wdms);
            tXzjg.setWdjd(wdjd);
            tXzjg.setWdwd(wdwd);
            tXzjg.setXzjgLb(xzjg_lb);

            if (!StringUtils.isEmpty(jgh)) tXzjg.setJgh(jgh);
            else tXzjg.setJgh("");

            if (!StringUtils.isEmpty(pid)){
                pXzjg = getBaseMapper().selectById(pid);
            }

            //如果有上级，级别为上级的级别+1
            if (!StringUtils.isEmpty(pid)){
                tXzjg.setPid(Long.valueOf(pid));
                tXzjg.setJb(pXzjg.getJb()+1);
            }else{
                //如果是修改，不改变级别，如果是新增，则都是第一级
                if ("0".equals(lx)) tXzjg.setJb(1L);
            }

            if (!StringUtils.isEmpty(xsxh)) tXzjg.setXh(Long.valueOf(xsxh));
            ResultInfo resultInfo;
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",jgmc);
            if ("1".equals(lx)){
                getBaseMapper().updateById(tXzjg);
                resultInfo = new ResultInfo(2, "修改成功！",rtnMap);
            }else{
                getBaseMapper().insert(tXzjg);
                resultInfo = new ResultInfo(1, "新增成功！",rtnMap);
            }
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo qy(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String id="",new_pid="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("new_pid")) {
                new_pid = jsonObject.getString("new_pid");
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TXzjg tXzjg;
            TXzjg pTXzjg;
            tXzjg = getBaseMapper().selectById(id);
            pTXzjg = getBaseMapper().selectById(new_pid);

            if (StringUtils.isEmpty(id) || null==tXzjg){
                ResultInfo resultInfo = new ResultInfo(500, "关键参数丢失！",null);
                return backRtn(resultInfo,loginId);
            }

            if (id.equals(new_pid)){
                ResultInfo resultInfo = new ResultInfo(500, "新上级不能选择自己！",null);
                return backRtn(resultInfo,loginId);
            }

            if (StringUtils.isEmpty(new_pid) || null==pTXzjg){
                getBaseMapper().setPidNull(tXzjg.getId());
            }else{
                tXzjg.setPid(Long.parseLong(new_pid));
                tXzjg.setJb(pTXzjg.getJb()+1);
                //更新自己的级别和父节点
                getBaseMapper().updateById(tXzjg);
            }

            //更新儿子们的级别
            getBaseMapper().updateJb(tXzjg.getId());


            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",tXzjg.getName());
            return backRtn(new ResultInfo(1, "迁移成功！",rtnMap),loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String menu_id="";
            if (jsonObject.containsKey("id")) {
                menu_id = jsonObject.getString("id");
            }
            if (StringUtils.isEmpty(menu_id)){
                ResultInfo resultInfo = new ResultInfo(500, "没有需要删除的信息！",null);
                return backRtn(resultInfo,loginId);
            }
            long sl = getBaseMapper().selectCount(new QueryWrapper<TXzjg>().eq("pid",menu_id.trim()));
            if (sl>=1){
                ResultInfo resultInfo = new ResultInfo(500, "请先删除下级数据！",null);
                return backRtn(resultInfo,loginId);
            }else {
                getBaseMapper().deleteById(menu_id);
                ResultInfo resultInfo = new ResultInfo(3, "删除成功！",null);
                return backRtn(resultInfo,loginId);
            }
        }
    }

    public List<TreeNode> getTreeSelect(){
        List<TXzjg> allCpflList = baseMapper.selectList(null);
        Map<Long, TreeNode> nodeMap = new HashMap<>();
        List<TreeNode> rootNodes = new ArrayList<>();

        // 1. 初始化所有节点，使用 value 而非 id
        for (TXzjg cpfl : allCpflList) {
            TreeNode node = new TreeNode();
            node.setValue(cpfl.getId());  // 将实体的 id 映射为节点的 value
            node.setName(cpfl.getName());
            node.setDisabled("0".equals(cpfl.getState()));
            node.setSelected(false);
            nodeMap.put(cpfl.getId(), node);
        }

        // 2. 构建父子关系
        for (TXzjg cpfl : allCpflList) {
            TreeNode currentNode = nodeMap.get(cpfl.getId());
            Long parentId = cpfl.getPid();

            if (parentId == null || !nodeMap.containsKey(parentId)) {
                rootNodes.add(currentNode);
            } else {
                TreeNode parentNode = nodeMap.get(parentId);
                parentNode.getChildren().add(currentNode);
            }
        }

        // 3. 设置特殊节点状态
        List<TreeNode> rtn = setExampleSpecialNodes(rootNodes);

        return rtn;
    }

    public List<TreeNode> getTreeSelect(QueryWrapper<TXzjg> tXzjgQueryWrapper){
        List<TXzjg> allCpflList = baseMapper.selectList(tXzjgQueryWrapper);
        Map<Long, TreeNode> nodeMap = new HashMap<>();
        List<TreeNode> rootNodes = new ArrayList<>();

        // 1. 初始化所有节点，使用 value 而非 id
        for (TXzjg cpfl : allCpflList) {
            TreeNode node = new TreeNode();
            node.setValue(cpfl.getId());  // 将实体的 id 映射为节点的 value
            node.setName(cpfl.getName());
            node.setDisabled("0".equals(cpfl.getState()));
            node.setSelected(false);
            nodeMap.put(cpfl.getId(), node);
        }

        // 2. 构建父子关系
        for (TXzjg tXzjg : allCpflList) {
            TreeNode currentNode = nodeMap.get(tXzjg.getId());
            Long parentId = tXzjg.getPid();

            if (parentId == null || !nodeMap.containsKey(parentId)) {
                rootNodes.add(currentNode);
            } else {
                TreeNode parentNode = nodeMap.get(parentId);
                parentNode.getChildren().add(currentNode);
            }
        }

        // 3. 设置特殊节点状态
        List<TreeNode> rtn = setExampleSpecialNodes(rootNodes);

        return rtn;
    }
}
